var MailPop = Class.create();
MailPop.prototype = {
    initialize: function(){
		this.init();
        this.is_tourial = false;
    },
	init: function() {
		this.PopAccounts = {};
		// this.getPopList = this.getPop3List;
	},
	displayText:{
		/*
		LEFT_DEFAULT_TEXT: USE_SYS.name == "sohu"?"代收其它邮箱，加<font color='red' style='font-weight:900'>50</font>分！":"一个邮箱管理更多邮件！",
		SETPOP_ATTACHINFO: USE_SYS.name == "sohu"?"<font color='red' style='font-weight:900'>HOT</font>：3月10日——3月24日，添加一个代收邮箱可获得<font style='font-weight:900' color='red'>50</font>积分奖励(重复添加无效)，最多可添加5个！":"",
		MANAGEPOP_ATTACHINFO: USE_SYS.name == "sohu"?"<font color='red' style='font-weight:900'>HOT</font>：3月10日——3月24日，添加一个代收邮箱可获得<font style='font-weight:900' color='red'>50</font>积分奖励(重复添加无效)，最多可添加5个！":"",
		SETPOPOK_ATTACHINFO_TITLE:USE_SYS.name == "sohu"?"":""
		*/
		LEFT_DEFAULT_TEXT:'一个邮箱管理更多邮件！',
		SETPOP_ATTACHINFO:'',
		MANAGEPOP_ATTACHINFO:'',
		SETPOPOK_ATTACHINFO_TITLE: ''
	},
	setPop3Account: function(is_alter) {
		//加过滤器 
		if(ExecFunc("pop3MailFilter","setPop3Account")===false){
			return;
		}
        //新手上路的垃圾js,alva
        //请注意,第二个参数被小生占用了....
        try{
            if(parseInt(arguments[1]) == 1){
                this.is_tourial = true;
            }
        }
        catch(e){
        }
		//如果pop账号超过6个不能添加
    	if (!is_alter && this.PopAccounts.length > 6) {
            _dialog.alert({info: "一个用户最多添加6个账号!"});
            return false;
        }
    	hiddenAllPanel();
    	$('mailConfiguration').innerHTML = SETPOP3TEMPLATE;
    	$('mailConfiguration').show();
		//附加提示信息
		if($("SETPOP_ATTACHINFO_AREA") && this.displayText["SETPOP_ATTACHINFO"]){
			$("SETPOP_ATTACHINFO_AREA").innerHTML = this.displayText["SETPOP_ATTACHINFO"];
		}
		var lib = {
			'qq.com': {pop3server: 'pop.qq.com'},
        	'sohu.com': {pop3server: 'pop3.sohu.com'},
        	'vip.sohu.com': {pop3server: 'pop3.vip.sohu.com'},
        	'tom.com': {pop3server: 'pop.tom.com'},
        	'126.com': {pop3server: 'pop.126.com'},
        	'163.com': {pop3server: 'pop.163.com'},
        	'sina.com': {pop3server: 'pop.sina.com'},
        	'gmail.com': {pop3server: 'pop.gmail.com',popport: 995},
        	'eyou.com': {pop3server: 'pop3.eyou.com'},
        	'china.com': {pop3server: 'pop.china.com'},
        	'21cn.com': {pop3server: 'pop.21cn.com'},
        	'yahoo.com': {pop3server: 'pop.mail.yahoo.com.cn'},
        	'yahoo.com.cn': {pop3server: 'pop.mail.yahoo.com.cn'},
        	'hotmail.com': {pop3server: 'pop3.live.com',popport: 995},
        	'live.com': {pop3server: 'pop3.live.com',popport: 995},
       		'live.com.cn': {pop3server: 'pop3.live.com',popport: 995},
        	'live.cn': {pop3server: 'pop3.live.com',popport: 995}
    	};
    	var _ipt_popuid = $('ID_IPT_POPUID'), _ipt_popserver = $('ID_IPT_POPSERVER'), _ipt_popport = $('ID_IPT_POPPORT');
		_ipt_popuid.onkeyup = _ipt_popuid.onfocus = function() {
			var _s = this.value.strip().split('@');
			if(_s.length != 2) return false;
			var _d = _s[1], _v = lib[_d];
			if(_v) {
				if (_v.pop3server) $('ID_IPT_POPSERVER').value = _v.pop3server;
            	_ipt_popport.value = (_v.popport ? _v.popport : 110);
			} else {
				_ipt_popserver.value = '';
           		_ipt_popport.value = '110';
			}
		};
	},
	setPop3AccountOK: function(popuid, poppwd) {
		var self = this;
    	hiddenAllPanel();
    	var tem = new Template(SETPOP3OKTEMPLATE);
    	var data = new Object();
    	data['POPUID'] = popuid;
    	$('mailConfiguration').innerHTML = tem.evaluate(data);
    	$('mailConfiguration').show();
    	//pop账号验证通过以后就在桶上添加文件夹
    	//如果文件夹创建失败 隔3秒钟就请求一次，最多3次
    	var n_create = 0;
    	(function(){
			var sf = arguments.callee;
        	folder_create({name: popuid}, function(r) {
            	n_create++;
            	//如果创建失败就重新创建最多3次
            	if (!r || typeof(r) != 'object' || r['is_success'] == undefined) {
                	if (n_create > 3) return;
                	setTimeout(sf, 3000);
                	return;
            	}
            	//返回结果正常就复位
            	n_create = 0;
            	if (r.is_success) {
                	data['FOLDERID'] = r['folder_id'];
                	$('mailConfiguration').innerHTML = tem.evaluate(data);
					//设置额外提示信息
					if($("SETPOPOK_ATTACHINFO_TITLEAREA") && self.displayText["SETPOPOK_ATTACHINFO_TITLE"]){
						$("SETPOPOK_ATTACHINFO_TITLEAREA").innerHTML +=  self.displayText["SETPOPOK_ATTACHINFO_TITLE"];
					}
                	r['name'] = popuid;
                	r['size'] = 0;
                	r['total'] = 0;
                	r['unread'] = 0;
					try {
						FoldersData['folders'].push(r);
					} catch(e) {}
                	self.setPopList();
					try {
						// 更新文件夹列表缓存
						folder_detail({}, function(ret) {
							FolderList = ret.folders;
							mailConference.F = ret;
							mailConference._folder();
						})
					} catch(e) {}
            	}
            	var _s = popuid.split('@'), _s1 = _s[1].split('.'), _pop_contact = $('ID_POPCONTACT_STATUS');
            	if (_s.length != 2) return;
            	if (_s1.length < 2) return;
            	var failStr = '<img src="' + MailConst.ALL + '/icon_ok.gif" width="16" height="16" align="absmiddle"/><span>抱歉，<strong class="brown">' + popuid + '</strong>的联系人导入失败。可能是对方服务器禁止导出联系人。</span>';
            	if (_s1[0] == 'sohu') {
                	_pop_contact.style.display = 'none';
                	return;
            	}
            	//导入地址本
            	import_other_addr({
                	name: _s[0],
                	passwd: poppwd,
                	replace: 0,
                	servername: _s1[0]
            	}, function(r) {
                	if (typeof(r) == 'string') return;
                	if (r.status) {
                    	_pop_contact.innerHTML = '<img src="' + MailConst.ALL + '/ok.gif" width="16" height="16" align="absmiddle"/><span>现在<strong class="brown">' + popuid + '</strong>的联系人已经导入到本邮箱中。</span>';
                    	mailAddressClass.initCache(true);
                	} else {
                    	_pop_contact.innerHTML = failStr;
                	}
            	});
        	});
            try{
                mailfolder.initEvent();
            }catch(e){}
    	})();
	},
    setPopList: function(){
        var PopIconCss = {
            "default": "icon-default",
            "163.com": "icon-from163",
            "263.com": "icon-from263",
            "126.com": "icon-from163",
            "yahoo.com": "icon-fromyahoo",
            "gmail.com": "icon-fromgmail",
            "sohu.com": "icon-fromsohu",
            "vip.sohu.com": "icon-fromsohu",
            "tom.com": "icon-fromtom",
            "263.com": "icon-from263",
            "sina.com": "icon-fromsina",
            "hotmail.com": "icon-fromhotmail",
            "qq.com": "icon-fromqq",
            "msn.com": "icon-frommsn"
        };
        var getIconByPopUid = function(uid) {
            if (!uid) return PopIconCss['default'];
            var i = uid.indexOf("@");
            if (i < 0) return PopIconCss['default'];
            var d = uid.substring(i + 1);
            return PopIconCss[d] ? PopIconCss[d] : PopIconCss['default'];
        };
        
        //是不是要显示右侧pop账号列表
        var flag = (arguments.callee.caller == this.getPop3List);
        // 是否有pop账号
        var hasPopAccount = false, self = this;
        var confunc = function(ret) {
			var sf = arguments.callee;
            //如果请求失败就显示旧数据
            if (!ret || typeof(ret) != 'object') ret = FoldersData;
            FoldersData = ret;
            var folders = ret.folders;
            FolderList = ret.folders;
            if (!folders || !(folders.length > 0)) return;
            // var n = folders.length;
            var s = document.createElement("div"), s1 = '', s2 = '', j = 0;
			
			folders.each(function(item) {
				// var r = folders[i];
                if (!IsEmail(item['name'], false)) return false;
                if (!self.PopAccounts[item['folder_id']]) {
                    self.PopAccounts[item['folder_id']] = {};
                }
                self.PopAccounts[item['folder_id']]['folder'] = item;
                j++;
                if (flag && $('mailfolder')) {
                    var tr = document.createElement("tr");
                    var td = document.createElement("td");
                    td2 = td.cloneNode(true);
                    td3 = td.cloneNode(true);
                    td4 = td.cloneNode(true);
                    td5 = td.cloneNode(true);
                    td.innerHTML = "<a style='cursor:pointer' onclick='changePanel(\"mailList\", " + item["folder_id"] + ");' hidefocus='true'>" + item["name"] + "</a>";
                    td2.innerHTML = item["unread"];
                    td3.innerHTML = item["total"];
                    td4.innerHTML = "[<a style='cursor:pointer;color:#A05C1D' onclick='mailPop.alterPop3Info(" + item["folder_id"] + ",\"" + item["name"] + "\")' hidefocus='true'>修改设置</a>]&nbsp;" +
                    "[<a style='cursor:pointer;color:#A05C1D' hidefocus='true' onclick='mailPop.delPop3Account(" +
                    item["folder_id"] +
                    ",\"" +
                    item["name"] +
                    "\")'>删除账号</a>]";
                    td5.innerHTML = "";
                    tr.appendChild(td);
                    tr.appendChild(td2);
                    tr.appendChild(td3);
                    tr.appendChild(td4);
                    tr.appendChild(td5);
                    self.PopAccounts[item["folder_id"]]["popstatus"] = td5;
                    $('mailfolder').firstChild.appendChild(tr);
                }
                
				/*
                var _s = '<li class="s_myfolder_' + item["folder_id"] + '" id="li' + item["folder_id"] + '" >' +
                '<a title="' +
                item["name"] +
                '" href="#mailList_' +
                item["folder_id"] +
                '" hidefocus="true">' +
                '<em>' +
                '<img width="17" height="17" align="absmiddle" src="' +
                MailConst.ALL +
                '/spacer.gif" class="am ' +
                getIconByPopUid(item["name"]) +
                '"/>' +
                '</em>' +
                (item['name'].length > 15 ? item['name'].truncate(15, '...') : item['name']) +
                '<b id="spnewmail_' +
                item["folder_id"] +
                '"></b>' +
                '</a>' +
                '</li>';
                */
				
				var _s = '<div id="folder_'+ item["folder_id"] +'" class="s_myfolder_' + item["folder_id"] + ' m-item" id="li' + item["folder_id"] + '" >' +
                '<a title="' +
                item["name"] +
                '" href="#mailList_' +
                item["folder_id"] +
                '" hidefocus="true">' +
                (item['name'].length > 15 ? item['name'].truncate(15, '...') : item['name']) +
                '<b id="spnewmail_' +
                item["folder_id"] +
                '"></b>' +
                '</a>' +
                '</div>';
				
                if (j > 3) 
                    s2 += _s;
                else 
                    s1 += _s;
                if (!hasPopAccount) hasPopAccount = true;
			});
            try{
            	mailfolder.initEvent();
            }catch(e){}
			
            if (flag) self.setReceivePopMailStatus();
			var _get_all_popmail = $('ID_BTN_GETALLPOPMAIL'), _daishou_mail = $('ID_DAISHOUMAIL');
            if (flag && !hasPopAccount && _get_all_popmail) {
				_get_all_popmail.disabled = true;
			}
            if (s1) {
                // _daishou_mail.style.padding = '';
                // _daishou_mail.className = 'menu_title';
                _daishou_mail.innerHTML = s1;
            } else {
                // _daishou_mail.style.padding = "3px 0 3px 10px";
                // _daishou_mail.className = "";
                _daishou_mail.innerHTML = '<div class="m-item">' +
                '<a hidefocus="true" href="javascript:;" class="s_daishoumanage">' +
                ' 一箱多邮  </a>' +
                '</div>';
            }
            
            if (s2 != "") {
                //包裹
                var s3 = document.createElement("div");
                s3.style.display = 'none';
                s3.innerHTML = s2;
                //折叠箭头
                var s4 = document.createElement('div');
                s4.style.textAlign = 'center';
                s4.style.cursor = 'pointer';
                s4.innerHTML = "<img src='" + MailConst.ALL + "/icon_bottom1.gif'/>";
                s4.onclick = function(){
                    var t = s3.style.display == "none";
                    s3.style.display = t ? "" : "none";
                    var imgs = this.getElementsByTagName("img");
                    var img = imgs.length > 0 ? imgs[0] : null;
                    if (img) {
                        img.src = MailConst.ALL + "/" + (t ? "icon_top1.gif" : "icon_bottom1.gif");
                        img.title = (t ? "折叠" : "展开");
                    }
                }
                _daishou_mail.appendChild(s3);
                _daishou_mail.appendChild(s4);
            }
            mailList.refreshFolderListNewMail();
        }
        if (FoldersData && !flag) {
			confunc(FoldersData);
		} else {
			folder_detail({}, confunc, function(){
				confunc(FoldersData)
			});
		}
    },
	
	//ui相关
	// 显示管理界面
	getPop3List: function(){
		// this.getPopList = arguments.callee;
    	hiddenAllPanel();
    	DOM.mailConfiguration.show();
    	DOM.mailConfiguration.innerHTML = POP3LISTTEMPLATE;
		if($("ID_MANAGEPOP_ATTACHINFO") && this.displayText["MANAGEPOP_ATTACHINFO"]){
			$("ID_MANAGEPOP_ATTACHINFO").innerHTML += "<dd>"+this.displayText["MANAGEPOP_ATTACHINFO"]+"</dd>";
		}
    	this.setPopList();
		ExecFunc("pop3MailFilter","getPop3List");
	},

	// 当文件夹是代收邮件的文件夹时，显示在列表页上方的信息
    setPopMailListTag: function(r) {
        if (!this.PopAccounts[mailList.currentFolder]) return;
        var popuid = this.PopAccounts[mailList.currentFolder + '']['folder']['name'];
        if (!IsEmail(popuid, false)) return;
        var o = $('spMailCount').parentNode;
        try {
            o.parentNode.style.height = '30px';
            if ($('mail_list_top')) 
                $('mail_list_top').style.display = 'none';
            if ($('mail_list_bottom')) 
                $('mail_list_bottom').style.display = 'none';
        } catch (e) {}
		var _t = 0, _u = 0;
		/*
		FoldersData.folders.each(function(item) {
			if(item.folder_id == mailList.currentFolder) {
				_t = item.total;
				_u = item.unread;
			}
		});
		*/
		FolderList.each(function(item) {
			if(item.folder_id == mailList.currentFolder) {
				_t = item.total;
				_u = item.unread;
			}
		});
        var s = '<p style="margin:7px;font-size:14px;">' +
        '<b>' +
        popuid +
        '</b>, ' +
        '[<a style="cursor:pointer;color:#A05C1D" onclick="mailPop.getPop3List()" hidefocus="true">管理</a>]&nbsp;&nbsp;' +
        '[<a style="cursor:pointer;color:#A05C1D" hidefocus="true" onclick="mailPop.getPopMail(\'' +
        mailList.currentFolder +
        '\',2)">收取</a>]' +
        '（共' +
        _t +
        '封，未读' +
        _u +
        '封）' +
        '<span id="ID_POPMAILSTATUS" class="brown" style="font-size:12px;">　' +
        '<img src="' +
        MailConst.ALL +
        '/ok.gif" width="16" height="16" align="absmiddle"/> ' +
        '收取完成，最近收取时间：2009-03-22 15：48' +
        '</span>' +
        '</p>';
        o.innerHTML = s;
        this.setReceivePopMailStatus();
    },
	
    getPopAccountInfo: function(k, v){
        for (i in this.PopAccounts) {
            var r = this.PopAccounts[i];
            if (!r) continue;
            if (r[k] && r[k] == v) 
                return r;
            else 
                if (!r[k]) {
                    for (j in r) 
                        if (r[j][k] == v) 
                            return r;
                }
        }
        return null;
    },
	
    getPopMailList: function(id, popuid) {
        try {
            if (popuid) {
                var p = this.getPopAccountInfo('name', popuid);
                if (p != null) {
                    id = p['folder']['folder_id'];
                }
            }
        } catch (e) { }
        if (id == null && isNaN(id)) return;
        changePanel('mailList', id);
    },

	// 同步指定文件夹下的邮件
    syncMailByFolderid: function(folder_id) {
        var params = {
            folder_id: folder_id
        };
        mail_check(params, function(r){
            var syncnum = 0;
            try {
                // syncnum = r['syncnum'];
				r[3]['folders'].each(function(item) {
					if(item.folder_id == folder_id) syncnum += item.unread;
				});
            } catch (e) {
                syncnum = 0;
            }
            //没有新邮件则返回
            if (syncnum == 0) 
                return;
            //如果用户正在浏览该文件夹邮件，则请求该文件夹下邮件列表
            if (!$('spnewmail_' + folder_id)) 
                return;
            mailList.changeFolderListNewMailByFolderId(folder_id, syncnum);
            mailList.refreshFolderListNewMail();
            if (mailList.currentFolder == folder_id) {
                changePanel('mailList', folder_id);
            }
        });
    },

	//ajax轮循
    getReceivePopMailStatus: function(folderid) {
        var ids = [];
        //获取所有要检索的popid
        for (i in this.PopAccounts) {
            try {
                if (!this.PopAccounts[i]) 
                    continue;
                var id = this.PopAccounts[i]['popid'];
                if (id && parseInt(id) > 0) {
                    if (this.PopAccounts[i]['popprogress'] && i != folderid && folderid != null) 
                        if (this.PopAccounts[i]['popprogress']['status'] != 1) 
                            continue;
                    ids[ids.length] = id;
                }
            }catch (e) {}
        }
        if (ids.length < 1) 
            return;
        var p = ids.join(",");
        //发送请求
        Pjax.isReq = true;
        Pjax.getPopMailStatus({
            id: p,
            t: (new Date()).getTime()
        }, function(r){
            Pjax.isReq = false;
            var t = false;
            if (typeof(r) == "string") 
                return;
            var n = r.length;
            for (var i = 0; i < n; i++) {
                var p = this.getPopAccountInfo('popid', r[i]['id']);
                p['popprogress'] = r[i];
                if (r[i].status == 1 && !t) 
                    t = true;
                if (r[i].status == 0) {
                    var f = this.getPopAccountInfo('popid', r[i]['id']);
                    //同步文件夹下邮件
                    if (r[i].lastpopcount > 0) 
                        this.syncMailByFolderid(f['folder']['folder_id']);
                }
            }
            this.setReceivePopMailStatus();
            if (t) {
				var self = this;
                var _t = setTimeout(function(){
					clearTimeout(_t);
					_t = null;
                    self.getReceivePopMailStatus('');
                }, 30000);
			}
        }.bind(this));
    },

	//设置请求全部pop状态
    setReceivePopMailStatus: function() {
        for (i in this.PopAccounts) {
            var p = this.PopAccounts[i];
            if (!p) continue;
            var id = p['popid'];
            var td = p['popstatus'];
            var progress = p['popprogress'];
            var s = '', s1 = '';
            if (id && parseInt(id) > 0) {
                if (progress) {
                    switch (progress["status"]) {
                        case 0:
                        case 3:
                        case 5:{
                            s = '<img src="' + MailConst.ALL + '/ok.gif" width="16" height="16" align="absmiddle"/> ' +
                            "收取完成";
                            s1 = s + "，最后收取时间：" + progress['lastpoptime'];
                            break;
                        }
                        case 1:{
                            s = '<img src="' + MailConst.ALL + '/loader.gif" width="16" height="16" align="absmiddle"/>' +
                            "正在收取邮件";
                            s1 = s + "，您可以先去进行其他工作 ！[<a style='cursor:pointer' hidefocus='true' onclick='mailPop.stopReceivePopMail(\"" + p["folder"]["folder_id"] + "\")'>停止收取<a>]";
                            break;
                        }
                        case 2:{
                            s = '<img src="' + MailConst.ALL + '/icon_ok.gif" width="16" height="16" align="absmiddle"/> ' +
                            "用户pop账号信息有误";
                            s1 = s + "，点击 “管理”重新设置！";
                            break;
                        }
                        case 4:{
                            s = '<img src="' + MailConst.ALL + '/icon_ok.gif" width="16" height="16" align="absmiddle"/>' +
                            "收取过程被您中止";
                            s1 = s + "...";
                            break;
                        }
                        case 11:{
                            s = '<img src="' + MailConst.ALL + '/loader2.gif" width="16" height="16" align="absmiddle"/>' +
                            "正在被用户停止";
                            s1 = s + "...";
                            break;
                        }
                        default:
                            {
                                s = '<img src="' + MailConst.ALL + '/icon_ok.gif" width="16" height="16" align="absmiddle"/> ' +
                                "下载失败";
                                s1 = s + "...";
                            }
                    }
                } else {
                    s = '<img src="' + MailConst.ALL + '/loader.gif" width="16" height="16" align="absmiddle"/> ' +
                    "开始发送请求";
                    s1 = s + "...";
                }
            } else {
                if (p['errcode'] == 2) {
                    s = '<img src="' + MailConst.ALL + '/icon_ok.gif" width="16" height="16" align="absmiddle"/> ' +
                    "该账号错误请删除";
                    s1 = s + "...";
                } else {
                    s = '<img src="' + MailConst.ALL + '/icon_ok.gif" width="16" height="16" align="absmiddle"/> ' +
                    "尚未发送请求";
                    s1 = s + "...";
                    this.getPopMail(i);
                }
            }
            if (td) td.innerHTML = s;
			var _pop_mailstatus = $('ID_POPMAILSTATUS');
            if (i == mailList.currentFolder && _pop_mailstatus) _pop_mailstatus.innerHTML = s1;
        }
    },

	//获取全部pop3账号邮件
    getPopMail: function(id, priority) {		
		//加过滤器 
		if(ExecFunc("pop3MailFilter","getPopMail")===false){
			return;
		}
        //判断有没有pop账号
        var hasPopAccount = false;
        for (var i in this.PopAccounts) {
            if (this.PopAccounts[i] && this.PopAccounts[i]['folder']) {
                hasPopAccount = true;
                break;
            }
        }
        if (!hasPopAccount) {
			var _get_all_popmail = $('ID_BTN_GETALLPOPMAIL');
            if (_get_all_popmail) _get_all_popmail.disabled = true;
            return;
        }
        var popuid = null, para = {
            userid: UID,
            priority: priority == null ? 1 : priority
        };
        try {
            if (id) {
                var p = this.PopAccounts[id + ''];
                popuid = p['folder']['name'];
                para['popuserid'] = popuid;
                if (this.getPopMail.caller != this.setReceivePopMailStatus) {
                    if (p['popprogress']) {
                        if (p['popprogress']['status'] == 1) {
                            _dialog.alert({
                                info: '正在复制该邮箱邮件。请过几分钟再来查看！'
                            });
                            return;
                        }
                    }
                }
            }
        } catch (e) {
            popuid = null;
        }
        
        Pjax.receivePopMail(para, function(r) {
            if (typeof(r) == 'string') return;
            try {
                if (!(r.length > 0)) {
                    if (popuid != null) {
                        var p = this.getPopAccountInfo('name', popuid);
                        p['errcode'] = r['errcode'];
                        this.setReceivePopMailStatus();
                    }
                    return;
                }
            } catch (e) {
                return;
            }
            var n = r.length;
            for (var i = 0; i < n; i++) {
                var p = this.getPopAccountInfo('name', r[i]['popuserid']);
                if (p != null) {
                    p['popid'] = r[i].id;
                }
            }
            this.setReceivePopMailStatus();
            this.getReceivePopMailStatus(id);
        }.bind(this));
    },

	//添加pop3账号
    createPopAccount: function() {
        var popuid = $('ID_IPT_POPUID').value;
        var poppwd = $('ID_IPT_POPPWD').value;
        var popserver = $('ID_IPT_POPSERVER').value;
        var popport = $('ID_IPT_POPPORT').value;
        var firstpopflag = $('ID_IPT_FIRSTPOP').checked;
        var reservecopy = $('ID_IPT_RESERVERCOPY').checked;
        var autopop = $('ID_IPT_AUTOPOP').checked;
        if (!popuid || !poppwd || !popserver || !popport) {
            _dialog.alert({
                info: "存在未填写的项！"
            });
            return false;
        }
        if (popuid == UID) {
            _dialog.alert({
                info: "不能添加本邮箱账号！"
            });
            return false;
        }
        if (!IsEmail(popuid, false)) {
            _dialog.alert({
                info: "邮箱格式不正确！"
            });
            return false;
        };
        for (i in this.PopAccounts) {
            var p = this.PopAccounts[i];
            if (p) {
                try {
                    if (p['folder']['name'] == popuid) {
                        _dialog.alert({
                            info: "该账号已经存在，请勿重复添加！"
                        });
                        return false;
                    }
                    
                } catch (e) {}
            }
        }
        $('ID_IPT_POPSUBMIT').disabled = true;
        var para = {
            'userid': UID,
            'popuserid': popuid,
            'poppassword': poppwd,
            'firstpopflag': firstpopflag ? 0 : 1,
            'autopop': autopop ? 0 : 1,
            'reservecopy': reservecopy ? 1 : 0,
            'popserver': popserver,
            'popport': popport
        };
        
        Pjax.addPopAccount(para, function(r) {
            $('ID_IPT_POPSUBMIT').disabled = false;
            if (r.errcode == 0) {
				this.setPop3AccountOK(popuid, poppwd);
			} else {
                if (r.errcode == 3) {
                    _dialog.alert({
                        info: "一个用户最多添加6个账号!"
                    });
                    return false;
                } else {
                    if (r.errcode == 4) {
                        this.setPop3AccountOK(popuid, poppwd);
                    } else {
                        var info = "添加失败！请检查：<br/>" +
                        "（1） 邮箱账号或密码是否正确；<br/>" +
                        "（2）      Pop3服务器填写是否正确；  <br/>" +
                        "如以上都正确则可能是对方使用了非常规的端口号，导致我方无法收取。<br/>";
                        _dialog.alert({info: info});
                    }
				}
			}
        }.bind(this));
        return true;
    },

    updatePopInfo: function() {
        var popserver = $("ID_IPT_POPSERVER").value;
        var popport = $("ID_IPT_POPPORT").value;
        var firstpopflag = $('ID_IPT_FIRSTPOP').checked;
        var reservecopy = $('ID_IPT_RESERVERCOPY').checked;
        var autopop = $('ID_IPT_AUTOPOP').checked;
        var popuid = $("ID_IPT_POPUID").value;
        var poppwd = $("ID_IPT_POPPWD").value;
        if (!popuid || !poppwd || !popserver || !popport) {
            _dialog.alert({
                info: "存在未填写的项！"
            });
            return false;
        }
        var para = {
            'userid': UID,
            'popuserid': popuid,
            'firstpopflag': firstpopflag ? 0 : 1,
            'autopop': autopop ? 0 : 1,
            'reservecopy': reservecopy ? 1 : 0,
            'popserver': popserver,
            'popport': popport
        };
        if (poppwd != '修改原始密码') 
            para['poppassword'] = poppwd;
        Pjax.updatePopAccount(para, function(r){
            if (r.errcode == 0) {
                $('ID_ALTERPOPACCOUNTMSG').style.display = '';
                var p = this.getPopAccountInfo('name', popuid);
                if (p) {
                    setTimeout(function(){
                        changePanel("mailList", p["folder"]["folder_id"]);
                    }, 3000);
                }
            } else {
                _dialog.alert({
                    info: "修改失败！"
                });
            }
        }.bind(this));
    },

	//修改pop3账号信息
    alterPop3Info: function(id, popuid){
		//加过滤器 
		if(ExecFunc("pop3MailFilter","alterPop3Info")===false){
			return;
		}
        try {
            var p = this.PopAccounts[id];
            if (p["popprogress"]) 
                if (p["popprogress"]["status"] == 1) {
                    _dialog.alert({
                        info: "正在收取邮件，请勿进行其它操作！"
                    });
                    return;
                }
            
        } catch (e) { }
        this.setPop3Account(true);
        $("ID_IPT_POPUID").disabled = true;
        $("ID_IPT_POPUID").value = $("ID_SPAN_POPUID").innerHTML = popuid;
        $("ID_IPT_POPPWD").value = "修改原始密码";
		var self = this;
        $('ID_IPT_POPSUBMIT').onclick = function(){
            self.updatePopInfo();
        }
        Pjax.getPopAccount({
            userid: UID,
            popuserid: popuid
        }, function(r){
            if (!r || !(r.length > 0)) 
                return;
            $("ID_IPT_POPSERVER").value = r[0].popserver;
            $("ID_IPT_POPPORT").value = r[0].popport;
            $('ID_IPT_FIRSTPOP').checked = (!(r[0].firstpopflag == 1));
            $('ID_IPT_RESERVERCOPY').checked = (r[0].reservecopy == 1);
            $('ID_IPT_AUTOPOP').checked = (!(r[0].autopop == 1));
        });
    },

	//清除pop3账号
	clearPop3Account: function(popuid){
	},

    //删除pop3账号
    delPop3Account: function(id, popuid) {
        try {
            var p = this.PopAccounts[id];
            if (p['popprogress']) 
                if (p['popprogress']['status'] == 1) {
                    _dialog.alert({
                        info: '正在收取邮件，请勿进行其它操作！'
                    });
                    return;
                }
            
        } catch (e) {}
        var para = {
            userid: UID,
            popuserid: popuid
        };
        this.delFromPop = function(){
            Pjax.delPopAccount(para, function(r){
                if (r.errcode == 0 || r.errcode == 100) {
                    this.delFromBucket();
                    this.PopAccounts[id] = null;
                } else {
                    _dialog.alert({info: '删除失败！'})
                }
            }.bind(this));
        }.bind(this);
        this.delFromBucket = function(){
            folder_delete({
                folder_id: id
            }, function(r){
                this.getPop3List();
                mailList.deleteFolderFromFolderList(id);
                mailList.refreshFolderListNewMail();
            }.bind(this))
        }.bind(this);
        //
        
        var p = this.PopAccounts[id];
        if (p && p['folder'] && p['folder']['total'] > 0) {
			var self = this;
            _dialog.confirm({
                info: "删除此账号，会把已经接收下来的邮件一并删除，您确认要继续吗？",
                click: function() {
					self.delFromPop();
				}
            });
        } else {
            this.delFromPop();
        }
    },

	//停止收信
    stopReceivePopMail: function(folder_id) {
        if (folder_id == null) return;
        var p = this.PopAccounts[folder_id];
        if (!p || !p['popid']) 
            return;
        var para = {
            userid: UID,
            id: p['popid']
        };
        if (p['popprogress'] && p['popprogress']['status'] != 1) return;
        if (!p['popprogress']) 
            p['popprogress'] = {};
        if (p['popprogress']['status'] == 1) 
            p['popprogress']['status'] = 11;
        this.setReceivePopMailStatus();
        Pjax.stopReceivePopMail(para, function(){
            if (!p["popprogress"]) 
                p["popprogress"] = {};
            if (p["popprogress"]["status"] == 1 || p["popprogress"]["status"] == 11) 
                p["popprogress"]["status"] = 4;
            this.setReceivePopMailStatus();
        }.bind(this))
    }
};
var mailPop = new MailPop();
